#include "prob.H"
#include "REMORA_prob_common.H"

#include "AMReX_ParmParse.H"
#include "AMReX_MultiFab.H"
#include "REMORA_IndexDefines.H"
#include "REMORA_DepthStretchTransform.H"

using namespace amrex;

ProbParm parms;

std::unique_ptr<ProblemBase>
amrex_probinit(const amrex_real* problo, const amrex_real* probhi)
{
    return std::make_unique<Problem>(problo, probhi);
}

/**
 * \brief Initializes bathymetry h and surface height Zeta
 */
void Problem::init_analytic_bathymetry (
        int lev, const amrex::Geometry& geom,
        SolverChoice const& m_solverChoice,
        REMORA const& remora,
        amrex::MultiFab& mf_h)
{
    auto geomdata = geom.data();
    bool EWPeriodic = geomdata.isPeriodic(0);
    bool NSPeriodic = geomdata.isPeriodic(1);

    // Must not be doubly periodic, and must have terrain
    AMREX_ALWAYS_ASSERT( !NSPeriodic || !EWPeriodic);
    AMREX_ALWAYS_ASSERT( !m_solverChoice.flat_bathymetry);

    // mf_h.setVal(geomdata.ProbHi(2));
    mf_h.setVal(50.0_rt);

    for ( MFIter mfi(mf_h, TilingIfNotGPU()); mfi.isValid(); ++mfi )
    {
        Array4<Real> const& h  = (mf_h).array(mfi);

        Box bx = mfi.tilebox();

        Box bxD = bx;
        bxD.makeSlab(2,0);

        Gpu::streamSynchronize();

        ParallelForRNG(bxD, [=] AMREX_GPU_DEVICE (int i, int j, int , auto engine)
        {
            h(i,j,0) = 50.0_rt;
        });

    } // mfi
}

/**
 * \brief Initializes custom sea surface height
 */
void Problem::init_analytic_zeta (
        int /*lev*/, const amrex::Geometry& /*geom*/,
        SolverChoice const& /*m_solverChoice*/,
        REMORA const& /*remora*/,
        MultiFab& mf_zeta)
{
    mf_zeta.setVal(0.0_rt);
}

void Problem::init_analytic_prob(
        int lev,
        const amrex::Geometry& geom,
        SolverChoice const& m_solverChoice,
        REMORA const& remora,
        amrex::MultiFab& mf_cons,
        amrex::MultiFab& mf_xvel,
        amrex::MultiFab& mf_yvel,
        amrex::MultiFab& mf_zvel)
{
    bool l_use_salt = m_solverChoice.use_salt;

    auto geomdata = geom.data();
    const int khi = geomdata.Domain().bigEnd()[2];

    bool EWPeriodic = geomdata.isPeriodic(1);
    bool NSPeriodic = geomdata.isPeriodic(0);

    auto T0 = m_solverChoice.T0;
    auto S0 = m_solverChoice.S0;
    for (MFIter mfi(mf_cons, TilingIfNotGPU()); mfi.isValid(); ++mfi)
    {
        const Box &bx = mfi.tilebox();
        AMREX_ALWAYS_ASSERT(bx.length()[2] == khi+1);

        Array4<      Real> const& state = mf_cons.array(mfi);
        Array4<      Real> const& x_vel = mf_xvel.array(mfi);
        Array4<      Real> const& y_vel = mf_yvel.array(mfi);
        Array4<      Real> const& z_vel = mf_zvel.array(mfi);

        Array4<const Real> const& z_r = remora.vec_z_r[lev]->const_array(mfi);

        ParallelFor(grow(grow(bx,0,1),1,1), [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
        {
            const auto prob_lo         = geomdata.ProbLo();
            const auto prob_hi         = geomdata.ProbHi();
            const auto dx              = geomdata.CellSize();

            const Real z = z_r(i,j,k);

            // Create bounding box for x and y to make spatially-dependent T and S
            const Real xcent = 0.5*(prob_lo[0] + prob_hi[0]);
            const Real ycent = 0.5*(prob_lo[1] + prob_hi[1]);

            const Real x  = prob_lo[0] + (i + 0.5) * dx[0] - xcent;
            const Real y  = prob_lo[1] + (j + 0.5) * dx[1];

            state(i,j,k,Temp_comp)=T0 + z / (9.8_rt * 1.7_rt);
            if (l_use_salt) {
                state(i,j,k,Salt_comp)=S0 + y / (9.8_rt * 760.0_rt);
            }

            // Set scalar = 0 everywhere
            state(i, j, k, Scalar_comp) = 0.0_rt;
        });

        const Box& xbx = surroundingNodes(bx,0);
        const Box& ybx = surroundingNodes(bx,1);
        const Box& zbx = surroundingNodes(bx,2);

        ParallelFor(grow(grow(xbx,1,1),0,1), [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
        {
            // Create bounding box for x and y to make spatially-dependent T and S
            const auto prob_lo         = geomdata.ProbLo();
            const auto prob_hi         = geomdata.ProbHi();
            const auto dx              = geomdata.CellSize();

            const Real xcent = 0.5*(prob_lo[0] + prob_hi[0]);
            const Real ycent = 0.5*(prob_lo[1] + prob_hi[1]);

            const Real z = z_r(i,j,k);
            // h(i,j,0) = -geomdata.ProbLo(2);
            const Real depth = 50.0_rt;

            const Real x  = prob_lo[0] + (i + 0.5) * dx[0];// - xcent;
            const Real y  = prob_lo[1] + (j + 0.5) * dx[1];// - ycent;

            const Real val1  = x * 6.28318530718_rt * 1.0e-5_rt;
            const Real val2  = y * 6.28318530718_rt * 1.0e-5_rt;
            x_vel(i, j, k) = (depth + z) * 0.01_rt + 0.05_rt * std::sin(val1) * std::sin(val2);
        });
        ParallelFor(ybx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
        {
            y_vel(i, j, k) = 0.0_rt;
        });

        ParallelFor(zbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
        {
            z_vel(i, j, k) = 0.0_rt;
        });
    }
    Gpu::streamSynchronize();
}

void Problem::init_analytic_vmix(
        int lev,
        const amrex::Geometry& /*geom*/,
        SolverChoice const& /*m_solverChoice*/,
        REMORA const& remora,
        MultiFab& mf_Akv, MultiFab& mf_Akt)
{
    for ( MFIter mfi((mf_Akv), TilingIfNotGPU()); mfi.isValid(); ++mfi )
    {
        Array4<Real> const& Akv = (mf_Akv).array(mfi);
        Array4<Real> const& Akt = (mf_Akt).array(mfi);
        Array4<const Real> const& z_w = remora.vec_z_w[lev]->array(mfi);
        Box bx = mfi.tilebox();
        bx.grow(IntVect(NGROW,NGROW,0));
        Gpu::streamSynchronize();
        amrex::ParallelFor(bx,
        [=] AMREX_GPU_DEVICE (int i, int j, int k)
        {
            Akv(i,j,k) = 2.0e-03_rt+8.0e-03_rt*std::exp(z_w(i,j,k)/150.0_rt);

            Akt(i,j,k,Temp_comp) = 1.0e-6_rt;
            Akt(i,j,k,Salt_comp) = 1.0e-6_rt;
            Akt(i,j,k,Scalar_comp) = 0.0_rt;
        });
    }
}

void Problem::init_analytic_hmix(
        int /*lev*/,
        const amrex::Geometry& /*geom*/,
        SolverChoice const& /*m_solverChoice*/,
        REMORA const& /*remora*/,
        MultiFab& mf_visc2_p,
        MultiFab& mf_visc2_r,
        MultiFab& mf_diff2)
{
    for ( MFIter mfi((mf_visc2_p), TilingIfNotGPU()); mfi.isValid(); ++mfi )
    {
      Array4<Real> const& visc2_p = (mf_visc2_p).array(mfi);
      Array4<Real> const& visc2_r = (mf_visc2_r).array(mfi);
      Array4<Real> const& diff2   = mf_diff2.array(mfi);
      Box bx = mfi.tilebox();
      bx.grow(IntVect(NGROW,NGROW,0));
      Gpu::streamSynchronize();

      int ncomp = mf_diff2.nComp();

      amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k)
      {
          visc2_p(i,j,k) = 2.0_rt;
          visc2_r(i,j,k) = 2.0_rt;

          for (int n = 0; n < ncomp; n++) {
              diff2(i,j,k,n) = 0.0_rt;
        }
      });
    }
}

void Problem::init_analytic_smflux(
        int lev,
        const amrex::Geometry& geom,
        SolverChoice const& m_solverChoice,
        REMORA const& remora,
        MultiFab& mf_sustr, MultiFab& mf_svstr)
{
    auto geomdata = geom.data();
    bool EWPeriodic = geomdata.isPeriodic(0);
    bool NSPeriodic = geomdata.isPeriodic(1);

    Real time = remora.get_t_old(lev);

    //If we had wind stress and bottom stress we would need to set these:
    Real tdays=time/Real(24.0*60.0*60.0);
    Real dstart=0.0_rt;
    Real userval=0.01_rt;
    Real mf_fcor=1.0e-4_rt;
    //It's possible these should be set to be nonzero only at the boundaries they affect

    // Don't allow doubly periodic in this case

    Real windamp_u = userval*std::sin(0.9_rt*mf_fcor*86400.0_rt*(tdays-dstart))/m_solverChoice.rho0;
    mf_sustr.setVal(windamp_u);
    mf_svstr.setVal(0.0_rt);
}
